package me.zhengjie.modules.system.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import me.zhengjie.modules.system.domain.MatchData;
import me.zhengjie.modules.system.domain.Product;
import me.zhengjie.modules.system.domain.PurchaseData;
import me.zhengjie.modules.system.excel.vo.MatchDataVo;
import me.zhengjie.modules.system.repository.MatchDataRepository;
import me.zhengjie.modules.system.repository.ProductRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class MatchDataListener extends AnalysisEventListener<MatchDataVo> {

    @Autowired
    private MatchDataRepository matchDataRepository;

    @Autowired
    private ProductRepository productRepository;

    private List<MatchData> matchDataList = new ArrayList<>();

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        matchDataList = new ArrayList<>();
        matchDataRepository.deleteAll();
    }

    @Override
    public void invoke(MatchDataVo matchDataVo, AnalysisContext analysisContext) {
        MatchData w = new MatchData();

        Product product = productRepository.findByProductCode(matchDataVo.getModel());
        if (product != null) {
            BeanUtils.copyProperties(product, w);
        }
        BeanUtils.copyProperties(matchDataVo, w);
        w.setId(null);
        matchDataList.add(w);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        matchDataRepository.saveAll(matchDataList);
    }
}
